import random
import socket
import requests
from MessageData import MessageData


def run():
    serversocket = socket.socket(
        socket.AF_INET, socket.SOCK_STREAM)

    host = "127.0.0.1"

    port = 8082

    # 绑定端口号
    serversocket.bind((host, port))

    # 设置最大连接数，超过后排队
    serversocket.listen(5)

    while True:
        # 建立客户端连接
        get_socket, addr = serversocket.accept()
        while True:
            message = get_socket.recv(8192).decode('utf-8')

            if not message:
                break

            data = data_get(message)

            msg = b"HTTP/1.1 200 OK\r\n"
            get_socket.send(msg)
        get_socket.close()


def data_get(message):
    temp = message.find('{')
    data = message[temp:]
    if data[-1] == '\"':
        data = data + '}'
    elif data[-1] != '}':
        data = data + '\"}'
    message_data = MessageData(data)
    message_data.print_data()
    #data_repeat(message_data)
    repeat_with_code(message_data)
    return message_data


def data_repeat(data: MessageData): # 第一版，无.help代码
    type_of_message = data.message_type
    if type_of_message == 'private':
        return post_msg_private(data.uid,
                                "锵锵！（消音）失踪ing！正在开发的人工智障绝赞为你复读!对着咱续火也是可以哒！")
    if type_of_message == 'group' and data.message != [] and data.message[0].get(
            'type') == 'at' and data.message[0].get('data').get('qq') == str(data.self_id):
        group_id = data.group_id
        get_message = data.message[-1].get('data').get('text')
        post_message = "[CQ:at,qq=" + str(
            data.uid) + "]\n" + "抱歉，您at的用户正在失踪！人工智障绝赞复读中:" + get_message
        return post_msg_group(group_id, post_message)


def repeat_with_code(data: MessageData):    # 第二版，待优化
    if data.message_type == 'private':
        post_message = ""
        for i in data.message:
            if i.get('type') == 'text' and i.get('data').get('text') != ' ':
                sub_text = i.get('data').get('text')
                if sub_text.replace(' ', '')[0] == '.':
                    if sub_text.find(' ') == 0:
                        sub_text = sub_text[1:]
                    oder = sub_text.split(' ')[0]
                    content = ''
                    if len(sub_text.split(' ')) == 2:
                        content = sub_text.split(' ')[1]
                    post_message = post_message + run_order(oder, content)
                    return post_msg_private(data.uid, post_message)
                else:
                    post_message = post_message + "锵锵！（消音）失踪ing！正在开发的人工智障绝赞为你复读!对着咱续火也是可以哒！\n输入.help获取功能列表w"
                    return post_msg_private(data.uid, post_message)
            else:
                post_message = post_message + "锵锵！（消音）失踪ing！正在开发的人工智障绝赞为你复读!对着咱续火也是可以哒！\n输入.help获取功能列表w"
                return post_msg_private(data.uid, post_message)
    if data.message_type == 'group' and data.message != [] and data.message[0].get(
            'type') == 'at' and data.message[0].get('data').get('qq') == str(data.self_id):
        post_message = "[CQ:at,qq=" + str(data.uid) + "]\n"
        for i in data.message:
            if i.get('type') == 'text' and i.get('data').get('text') != ' ':
                sub_text = i.get('data').get('text')
                if sub_text.replace(' ', '')[0] == '.':
                    if sub_text.find(' ') == 0:
                        sub_text = sub_text[1:]
                    oder = sub_text.split(' ')[0]
                    content = ''
                    if len(sub_text.split(' ')) == 2:
                        content = sub_text.split(' ')[1]
                    post_message = post_message + run_order(oder, content)
                    return post_msg_group(data.group_id, post_message)
                else:
                    post_message = post_message + "抱歉，您at的用户正在失踪！人工智障绝赞复读中:" + sub_text + "\n输入.help获取功能列表"
                    return post_msg_group(data.group_id, post_message)
            elif i.get('data').get('text') != ' ':
                post_message = post_message + "抱歉，您at的用户正在失踪！人工智障绝赞复读中:"  + "\n输入.help获取功能列表"
                return post_msg_group(data.group_id, post_message)


def run_order(oder, content):
    if oder == '.help':
        result = ".roll掷骰\n更多功能开发中"
        return result
    if oder == '.roll':
        if content != '' and judge_roll_code(content):
            temp = content.split('d')
            result = ""
            for i in range(int(temp[0])):
                result = result + str(random.randint(1, int(temp[1]))) + "!"
            return result
        elif content == '':
            result = str(random.randint(1, 6))
            return result
        else:
            return "格式出错（.roll{空格}{投掷几个骰子}d{1到你所需要的最大点数}）！.roll默认1d6。"
    return "未知指令"

def judge_roll_code(content):
    return (len(content) >= 3 and
            content.count('d') == 1 and
            content[0] != 'd' and
            content[-1] != 'd' and
            content.split('d')[0].isdigit() and
            content.split('d')[1].isdigit())


def post_msg_private(uid: int, msg):
    url = 'http://127.0.0.1:8083/send_msg'
    data = {"user_id": uid, "message": msg}  # 替换为你要发送的POST数据
    response = requests.post(url, data=data)
    data = response.text  # 获取响应结果
    return data


def post_msg_group(group_id: int, msg):
    url = 'http://127.0.0.1:8083/send_group_msg'
    data = {"group_id": group_id, "message": msg}
    response = requests.post(url, data=data)
    data = response.text
    return data


run()
